/*
* SMILParser
*
* Version 1.0
*
* Programmers: Jesse Louderback, Noah Pham, Chad Carpenter, and Marc Hindman
*/
package parser;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import Message.SMILMessage;
import Message.SMILObject;
import Message.SMILRegion;

public class SMILParser {
	private static SMILMessage message;
	private static String fileLoc;
	
	public SMILParser(String fileLoc) {
		SMILParser.fileLoc = fileLoc;
		message = new SMILMessage();
	}
	
	public SMILMessage parse() {		
		try {
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
													   .newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			org.w3c.dom.Document doc = docBuilder.parse(new File(fileLoc));

			// normalize text representation
			doc.getDocumentElement().normalize();
			
			getNodeData(doc.getElementsByTagName("img"));		
			getNodeData(doc.getElementsByTagName("text"));
			getNodeData(doc.getElementsByTagName("audio"));
			getRegionData(doc.getElementsByTagName("region"));
		} catch (SAXParseException err) {
			System.out.println("** Parsing error" + ", line "
							   + err.getLineNumber() + ", uri " + err.getSystemId());
			System.out.println(" " + err.getMessage());
		} catch (SAXException e) {
			Exception x = e.getException();
			((x == null) ? e : x).printStackTrace();
		} catch (Throwable t) {
			t.printStackTrace();
		}
		
		return message;
	}

	protected void getNodeData(NodeList Nodes) {
		SMILObject obj;
		for (int s = 0; s < Nodes.getLength(); s++) {
			Node singleNode = Nodes.item(s);
			if (singleNode.getNodeType() == Node.ELEMENT_NODE) {
				Element element = (Element) singleNode;
				obj = new SMILObject(element.getNodeName(), 
									 Float.parseFloat(element.getAttribute("begin")),
									 				  Float.parseFloat(element.getAttribute("dur")), 
									 				  				   element.getAttribute("src"), 
									 				  				   element.getAttribute("region"));
				message.AddObject(obj);
			}
		}
	}
	
	private void getRegionData(NodeList Nodes) {
		SMILRegion obj;
		for (int s = 0; s < Nodes.getLength(); s++) {
			Node singleNode = Nodes.item(s);
			if (singleNode.getNodeType() == Node.ELEMENT_NODE) {
				Element element = (Element) singleNode;
				 
				obj = new SMILRegion(element.getAttribute("id"),
									 Float.parseFloat(element.getAttribute("left")), 
									 				  Float.parseFloat(element.getAttribute("top")), 
									 				  Float.parseFloat(element.getAttribute("height")), 
									 				  Float.parseFloat(element.getAttribute("width")));
				message.addRegion(element.getAttribute("id"), obj);
			}
		}
	}
}
